package cn.huimin.httpClient.impl;

import cn.huimin.httpClient.AbstractHttpClient;
import cn.huimin.httpClient.IHttpClient;
import cn.huimin.httpClient.ex.URLEmptyException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Martin on 2017-2-27.
 */
public class HMGetRequest extends AbstractHttpClient {

    private static Log logger = LogFactory.getLog(HMGetRequest.class);

    private HMGetRequest() {
    }

    public static IHttpClient getInstance() {

        return new HMGetRequest();
    }

    @Override
    public RequestMethod getMethodType() {
        return RequestMethod.GET;
    }

    @Override
    public String sendData() throws URLEmptyException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httpget.
        HttpGet httpget = new HttpGet(client.getGetUrl().toString());


        //设置请求头
        if (client.getHeader() != null && client.getHeader().size() > 0) {
            Map<String, String> map = client.getHeader();
            for (String key : map.keySet()) {
                httpget.setHeader(key, map.get(key));
            }
        }


        logger.info("Executing Request " + httpget.getURI());
        // 执行get请求.
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                logger.info("---------------------------------------------");
                responseStatus = response.getStatusLine().getStatusCode() + "";
                logger.info("Response Status: " + responseStatus);
                responseData = EntityUtils.toString(entity, encoding);
                logger.info("Response content: " + responseData);
                logger.info("---------------------------------------------");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseData;
    }
}
